package com.laicunba.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.laicunba.pojo.RegistryDO;
import com.laicunba.pojo.vo.LocalCachedVO;
import com.laicunba.service.RegistryService;
import com.laicunba.util.CacheUtil;

@Service
public class RegistryServiceImpl extends BaseServiceImpl implements RegistryService {
	private static Map<String, LocalCachedVO> LOCAL_CACHE_MAP = new HashMap<String, LocalCachedVO>();

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public Map<String, String> likeKey(String startsWith) {
		List<Map<String, String>> list = queryDao.selectList("REGISTRY.likeKey", startsWith);
		Map<String, String> rs = new HashMap();
		for (Map<String, String> map : list) {
			rs.put(map.get("id"), map.get("val"));
		}
		return rs;
	}

	@Override
	public boolean create(String id, String val) {
		RegistryDO registry = new RegistryDO();
		registry.setId(id);
		registry.setVal(val);
		registry.setVisible(true);
		return create(registry);
	}

	@Override
	public boolean update(String id, String val) {
		RegistryDO registry = new RegistryDO();
		registry.setId(id);
		registry.setVal(val);
		registry.setVisible(true);
		return updateSkipCheckOwner(registry);
	}

	@Override
	public Map<String, String> find(String[] key) {
		List<Map<String, String>> list = queryDao.selectList("REGISTRY.find", key);
		Map map = new HashMap();
		if (list != null) {
			for (Map<String, String> tmp : list) {
				map.put(tmp.get("id"), tmp.get("val"));
			}
		}
		return map;
	}

	@Override
	public List<RegistryDO> list() {
		return queryDao.selectList("REGISTRY.list", null);
	}

	@Override
	public String getFromCache(String id) {
		LocalCachedVO localCachedVO = LOCAL_CACHE_MAP.get(id);
		if (localCachedVO != null && localCachedVO.getExpiredTime() > System.currentTimeMillis()) {
			return localCachedVO.getVal();
		}
		String val = CacheUtil.getAttribute("REGISTRY_" + id);
		if (val != null) {
			LOCAL_CACHE_MAP.put(id, new LocalCachedVO(id, val, System.currentTimeMillis() + 60000));
			return val;
		}
		RegistryDO registryDO = get(RegistryDO.class, id);
		if (registryDO != null) {
			LOCAL_CACHE_MAP.put(id, new LocalCachedVO(id, registryDO.getVal(), System.currentTimeMillis() + 60000));
			CacheUtil.setAttribute("REGISTRY_" + id, registryDO.getVal());
			return registryDO.getVal();
		}
		return null;
	}

	@Override
	public void clearCache(String id) {
		CacheUtil.removeAttribute("REGISTRY_" + id);
	}

	@Override
	public List<RegistryDO> like(String idPrex, String likeVal) {
		Map<String, String> map = new HashMap();
		map.put("idPrex", idPrex);
		map.put("likeVal", likeVal);
		return queryDao.selectList("REGISTRY.like", map);
	}
}
